package logic

import (
	"context"
	"edu/models/mysql"

	"edu/edurpc/edurpc"
	"edu/edurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelListLogic {
	return &NovelListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NovelListLogic) NovelList(in *edurpc.NovelListRequest) (*edurpc.NovelListResponse, error) {
	offset := (in.Page - 1) * in.Size
	var novels []mysql.Novel
	query := mysql.DB.Where("user_id = ?", in.UserId)
	if in.Title != "" {
		query = query.Where("title like ?", "%"+in.Title+"%")
	}
	if in.Category != "" {
		query = query.Where("category like ?", "%"+in.Category+"%")
	}
	if in.OrderBy != "" {
		if in.OrderBy == "desc" || in.OrderBy == "asc" {
			query = query.Order("created_at " + in.OrderBy)
		}
	}
	query.Offset(int(offset)).Limit(int(in.Size)).Find(&novels)
	var count int64
	query.Count(&count)
	var novelList []*edurpc.NovelList
	for _, novel := range novels {
		list := edurpc.NovelList{
			Title:    novel.Title,
			Category: novel.Category,
			Info:     novel.Info,
			Refer:    novel.Refer,
			Image:    novel.Image,
		}
		novelList = append(novelList, &list)
	}
	return &edurpc.NovelListResponse{
		List:  novelList,
		Count: count,
	}, nil
}
